﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;

namespace Common.Core
{
    public class ConfigurationUtil
    {

        private static  IConfiguration? _configuration;

        public ConfigurationUtil(IWebHostEnvironment hostEnvironment)
        {
            //如果你把配置文件 是 根据环境变量来分开了，可以这样写
            string basePath = "appsettings.json";
            string subPath = $"appsettings.{hostEnvironment.EnvironmentName}.json";

            _configuration = new ConfigurationBuilder()
                .SetBasePath(AppContext.BaseDirectory)
                .Add(new JsonConfigurationSource { Path = basePath, Optional = false, ReloadOnChange = true })
                .Add(new JsonConfigurationSource { Path = subPath, Optional = false, ReloadOnChange = true })
                .Build();
        }



        /// <summary>
        /// 封装要操作的字符
        /// </summary>
        /// <param name="sections">节点配置</param>
        /// <returns></returns>
        public static string App(params string[] sections)
        {
            try
            {

                if (sections.Any())
                {
                    return _configuration?[string.Join(":", sections)];
                }
            }
            catch (Exception) { }

            return "";
        }

        /// <summary>
        /// 递归获取配置信息数组
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sections"></param>
        /// <returns></returns>
        public static List<T> App<T>(params string[] sections)
        {
            List<T> list = new List<T>();
            // 引用 Microsoft.Extensions.Configuration.Binder 包
            _configuration.Bind(string.Join(":", sections), list);
            return list;
        }

        public static string GetSection(string key)
        {
            return _configuration.GetValue<string>(key);
        }
    }
}
